package com.xdtech.sys.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.thoughtworks.xstream.XStream;
import com.xdtech.common.fomat.TreeBuilder;
import com.xdtech.common.utils.HibernateHelper;
import com.xdtech.sys.model.FilterGroup;
import com.xdtech.sys.model.FilterRule;
import com.xdtech.sys.model.FilterTranslator;
import com.xdtech.sys.model.Resource;
import com.xdtech.sys.model.UserGroup;
import com.xdtech.sys.service.FilterRuleService;
import com.xdtech.sys.service.FilterTranslatorService;
import com.xdtech.sys.service.ResourceService;
import com.xdtech.sys.service.RoleService;
import com.xdtech.sys.service.UserGroupService;
import com.xdtech.sys.service.UserService;
import com.xdtech.sys.util.SysConstants;
import com.xdtech.sys.vo.FilterGroupItem;
import com.xdtech.sys.vo.FilterRuleItem;
import com.xdtech.sys.vo.FilterTranslatorItem;
import com.xdtech.sys.vo.ResourceItem;
import com.xdtech.sys.vo.RoleItem;
import com.xdtech.sys.vo.UserItem;
import com.xdtech.sys.vo.UsergroupItem;
import com.xdtech.web.model.ComboBox;
import com.xdtech.web.model.Pagination;
import com.xdtech.web.model.ResultMessage;
import com.xdtech.web.model.TreeItem;

/**
 * 
 * @author max.zheng
 * @create 2015-03-18 13:53:54
 * @since 1.0
 * @see
 */
@Controller
@Scope("prototype")
public class ResourceController {
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private FilterRuleService filterRuleService;
	@Autowired
	private FilterTranslatorService filterTranslatorService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserGroupService userGroupService;
	@RequestMapping(value="/resource.do",params = "resource")
	public ModelAndView skipResource() {
		return new ModelAndView("sys/resource/resource_ftl");
	}
	
	@RequestMapping(value="/resource.do",params="loadList")
	@ResponseBody
	public Map<String, Object> loadList(HttpServletRequest request,Pagination pg) {
		Map<String, Object> results = null;
		if (StringUtils.isEmpty(request.getParameter("page"))) {
			//不分页处理
			results = resourceService.loadPageAndCondition(null, null);
		}else {
			results = resourceService.loadPageAndCondition(pg, null);
		}
		
		return results;
	}
	
	@RequestMapping(value="/resource.do",params = "editResource")
	public ModelAndView editResource(HttpServletRequest request,Long resourceId) {
//		List<String> tableNames = HibernateHelper.getTableNames();
		int ruleIndex = 0;
		int groupIndex = 0;
		if (resourceId!=null) {
			ResourceItem item = resourceService.loadResourceItem(resourceId);
			request.setAttribute("resourceItem",item );
			request.setAttribute("tableName", item.getKey());
//			FilterRule rule = filterRuleService.getRuleByResourceKey(item.getKey());
//			request.setAttribute("rule", rule);
			FilterTranslator translator = filterTranslatorService.getTranslatorByResourceId(resourceId);
			XStream xstream = new XStream(); 
		    FilterTranslatorItem translatorItem = (FilterTranslatorItem) xstream.fromXML(translator.getXml());
		    List<FilterGroupItem> groupItems = translatorItem.getGroups();
		    groupIndex = groupItems.size();
		    for (FilterGroupItem filterGroupItem : groupItems)
			{
				ruleIndex += filterGroupItem.getRules().size();
			}
		    
		    request.setAttribute("groups", groupItems);
		}
		request.setAttribute("groupIndex", groupIndex);
	    request.setAttribute("ruleIndex", ruleIndex);
	    //加载用户 角色 用户组 三者列表
	    List<UserItem> users = userService.loadAllUserItem();
	    List<RoleItem> roles = roleService.loadAllRoles();
	    List<UsergroupItem> usergroups = userGroupService.loadAllUserGroupItems();
	    request.setAttribute("roles", roles);
	    request.setAttribute("users", users);
	    request.setAttribute("usergroups", usergroups);
		return new ModelAndView("sys/resource/editResource_ftl");
	}
	
	@RequestMapping(value="/resource.do",params = "loadTableNames")
	@ResponseBody
	public List<ComboBox> loadTableNames(String tableName) {
		List<String> tableNames = HibernateHelper.getTableNames();
		List<ComboBox> comboBoxs = new ArrayList<ComboBox>();
		for (String tn : tableNames)
		{
			comboBoxs.add(new ComboBox(tn, tn, tn.equals(tableName)));
		}
		return comboBoxs;
	}
	
	@RequestMapping(value="/resource.do",params = "getSelectFieldsByTableName")
	@ResponseBody
	public List<ComboBox> getSelectFieldsByTableName(String tableName,String value) {
		List<ComboBox> comboBoxs = new ArrayList<ComboBox>();
		if (StringUtils.isNotEmpty(tableName))
		{
			List<String> columns = HibernateHelper.getColumnNames(tableName);
			for (String column : columns)
			{
				comboBoxs.add(new ComboBox(column, column, column.equals(value)));
			}
		}
		addCommonComboList(comboBoxs,value);
		return comboBoxs;
	}
	
	/**
	 * 
	 * @author max.zheng
	 * @create 2015-3-18下午10:51:25
	 * @modified by
	 * @param comboBoxs
	 */
	private void addCommonComboList(List<ComboBox> comboBoxs,String value) {
		comboBoxs.add(new ComboBox(SysConstants.CURRENT_USER_ID, "登录用户", SysConstants.CURRENT_USER_ID.equals(value)));
		comboBoxs.add(new ComboBox(SysConstants.CURRENT_ROLE_IDS, "登录角色", SysConstants.CURRENT_ROLE_IDS.equals(value)));
		comboBoxs.add(new ComboBox(SysConstants.CURRENT_GROUP_IDS, "登录用户组", SysConstants.CURRENT_GROUP_IDS.equals(value)));
	}

	@RequestMapping(value="/resource.do",params = "loadRoles")
	@ResponseBody
	public List<ComboBox> loadRoles(String value) {
		List<ComboBox> comboBoxs = new ArrayList<ComboBox>();
		List<RoleItem> items = roleService.loadAllRoles();
		for (RoleItem item : items)
		{
			comboBoxs.add(new ComboBox(item.getId().toString(), item.getName(), item.getId().toString().equals(value)));
		}
		return comboBoxs;
	}
	
	@RequestMapping(value="/resource.do",params = "loadUsers")
	@ResponseBody
	public List<ComboBox> loadUsers(String value) {
		List<ComboBox> comboBoxs = new ArrayList<ComboBox>();
		List<UserItem> items = userService.loadAllUserItem();
		for (UserItem item : items)
		{
			comboBoxs.add(new ComboBox(item.getId().toString(), item.getName(), item.getId().toString().equals(value)));
		}
		return comboBoxs;
	}
	
	
	@RequestMapping(value="/resource.do",params = "loadRuleValues")
	@ResponseBody
	public List<TreeItem> loadRuleValues(String fieldValue,String value) {
		List<TreeItem> items = new ArrayList<TreeItem>();
		TreeItem item = null;
		TreeItem pItem = null;
		if (SysConstants.CURRENT_ROLE_IDS.equals(fieldValue))
		{
			List<RoleItem> roleItems = roleService.loadAllRoles();
			for (RoleItem roleItem : roleItems)
			{
				item = new TreeItem();
				item.setId(roleItem.getId());
				item.setText(roleItem.getName());
				item.setParent(pItem);
				if (null != value)
				{
					item.setChecked(value.contains(roleItem.getId().toString()));
				}
				items.add(item);
			}
		}else if (SysConstants.CURRENT_GROUP_IDS.equals(fieldValue))
		{
			Iterable<UserGroup> usergroups = userGroupService.loadUserGroups();
			for (UserGroup userGroup : usergroups) {
				item = new TreeItem();
				item.setId(userGroup.getId());
				item.setText(userGroup.getName());
				item.setContent(userGroup.getDescription());
				if (null != value)
				{
					item.setChecked(value.contains(userGroup.getId().toString()));
				}
				if (userGroup.getParent()!=null) {
					pItem = new TreeItem(userGroup.getParent().getId());
				}else {
					pItem = null;
				}
				item.setParent(pItem);
				items.add(item);
			}
		}
//		else if (SysConstants.CURRENT_USER_ID.equals(fieldValue))
		else
		{
			//拼配不到的都默认是加载用户规则连接关系
			List<UserItem> userItems = userService.loadAllUserItem();
			for (UserItem userItem : userItems)
			{
				item = new TreeItem();
				item.setId(userItem.getId());
				item.setText(userItem.getName());
				item.setParent(pItem);
				if (null != value)
				{
					item.setChecked(value.contains(userItem.getId().toString()));
				}
				items.add(item);
			}
		}
		
		return TreeBuilder.newTreeBuilder(TreeItem.class, Long.class).buildToTreeList(items);
	}
	
	@RequestMapping(value="/resource.do",params = "saveResource")
	@ResponseBody
	public ResultMessage saveResource(ResourceItem item) {
		ResultMessage r = new ResultMessage();
		if (resourceService.saveOrUpdateResource(item)) {
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	
	@RequestMapping(value="/resource.do",params = "deleteResourceItems")
	@ResponseBody
	public ResultMessage deleteResourceItems(String ids) {
		ResultMessage r = new ResultMessage();
		if (StringUtils.isNotEmpty(ids)) {
			String[] tempIds = ids.split(",");
			List<Long> resourceIds = new ArrayList<Long>();
			for (String id : tempIds) {
				resourceIds.add(Long.valueOf(id));
			}
			resourceService.deleteResourceInfo(resourceIds);
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}

	@RequestMapping(value="/resource.do",params = "saveResoucePermissionInfo")
	@ResponseBody
	public ResultMessage saveResoucePermissionInfo(HttpServletRequest request) {
		ResultMessage r = new ResultMessage();
		//id=&type=table&key=TRAN_ORDER
			//&splitgp=gp&groupOption=and
				//&splitrl=rl&ruleField=currentUserId&ruleType=eq&ruleValue=1
				//&splitrl=rl&ruleField=currentRoleIds&ruleType=in&ruleValue=2&ruleOption=and
			//&splitgp=gp&groupOption=and
				//&splitrl=rl&ruleField=currentUserId&ruleType=in&ruleValue=1
		String formData = request.getParameter("formData");
//		URLEncoder
		try
		{
			formData = URLDecoder.decode(formData,"UTF-8");
			System.out.println(formData);
		}
		catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Resource resource = new Resource();
		FilterTranslator translator = new FilterTranslator();
		createResourcePermissionData(formData, resource, translator);
		resourceService.createResourcePermission(resource,translator);
		return r;
	}
	
	private void createResourcePermissionData(String formData,Resource resource,FilterTranslator translator) {
		String[] formRescource = formData.split("splitgp=gp");
		List<FilterGroup> groups = new ArrayList<FilterGroup>();
		Map<String, String> params = null;
		
		List<FilterGroupItem> groupItems = new ArrayList<FilterGroupItem>();
		if (formRescource.length>0) {
			for (int i = 0; i < formRescource.length; i++) {
				System.out.println(formRescource[i]);
				if (i==0) {
					//id=&type=table&key=TRAN_ORDER&
					params = strParamsToMap(formRescource[i]);
					resource.setId(params.get("id")!=null?Long.valueOf(params.get("id")):null);
					resource.setKey(params.get("key"));
					resource.setType(params.get("type"));
				}else {
					String[] groupContent = formRescource[i].split("splitrl=rl");
					FilterGroup group = new FilterGroup();
					FilterGroupItem groupItem = new FilterGroupItem();
					List<FilterRule> rules = new ArrayList<FilterRule>();
					for (int j = 0; j < groupContent.length; j++) {
						params = strParamsToMap(groupContent[j]);
						if (j==0) {
							//分组组信息
							//groupOption=and
							group.setOption(params.get("groupOption"));
							groups.add(group);
							groupItem = FilterGroupItem.createItem(group);
							groupItems.add(groupItem);
						}else {
							//&ruleField=currentRoleIds&ruleType=in&ruleValue=2&ruleOption=and
							FilterRule rule = new FilterRule();
							rule.setField(params.get("ruleField"));
							rule.setOption(params.get("ruleOption"));
							rule.setValue(params.get("ruleValue"));
							rule.setType(params.get("ruleType"));
							rules.add(rule);
						}
					}
					group.setFilterRules(rules);
					groupItem.setRules(FilterRuleItem.createItems(rules));
				}
			}
			//设置组
			translator.setGroups(groups);
			//创建内容
			translator.createText();
		    XStream xstream = new XStream();
	        String xml = xstream.toXML(new FilterTranslatorItem(groupItems, null)); 
	        translator.setXml(xml.toString());
		}
	}
	/**
	 * 将数据ruleField=currentRoleIds&ruleType=in&ruleValue=2&ruleOption=and用&切割转map
	 * @author max.zheng
	 * @create 2015-3-21下午11:32:53
	 * @modified by
	 * @param resourceParams
	 * @return
	 */
	private static Map<String, String> strParamsToMap(String content) {
		// id=&type=table&key=TRAN_ORDER&
		Map<String, String> parmasMap = new HashMap<String, String>();
		String[] resourceParams = content.split("&");
		for (int i = 0; i < resourceParams.length; i++) {
			String str = resourceParams[i];
			String[] temp = str.split("=");
			if (temp.length>1) {
				parmasMap.put(temp[0], temp[1]);
			}else {
				parmasMap.put(temp[0], null);
			}
		}
		return parmasMap;
	}
}
